package cn.itsource.itsource.service.impl;

import cn.itsource.itsource.domain.Pet;
import cn.itsource.itsource.domain.PetDetail;
import cn.itsource.itsource.domain.Shop;
import cn.itsource.itsource.mapper.PetDetailMapper;
import cn.itsource.itsource.mapper.PetMapper;
import cn.itsource.itsource.mapper.ShopMapper;
import cn.itsource.itsource.query.PetQuery;
import cn.itsource.itsource.service.IPetService;
import cn.itsource.itsource.util.PageList;
import cn.itsource.itsource.vo.PetVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;


@Service
@Transactional
public class PetServiceImpl implements IPetService {
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private PetDetailMapper petDetailMapper;
    @Autowired
    private ShopMapper shopMapper;



    @Override
    public PageList findPage(PetQuery query) {
        //1.拼接条件
        Example example = new Example(Pet.class);
        Example.Criteria and = example.and();
        if (StringUtils.isNotBlank(query.getName())) {
            and.andLike("name", "%" + query.getName() + "%");
        }
        if (query.getState() != null) {
            and.andEqualTo("state", query.getState());
        }
        //分页条件
        PageHelper.startPage(query.getCurrPage(), query.getPageSize());
        PageInfo<Pet> pageInfo = new PageInfo<>(petMapper.selectByExample(example));
        return new PageList(pageInfo.getTotal(), pageInfo.getList());

    }

    @Override
    public PageList queryHomePage(PetQuery query) {
        //【已上架】
        Example example = new Example(Pet.class);
        Example.Criteria and = example.and();
        //固定条件：已上架
        and.andEqualTo("state", 1);//1表示：上架宠物

        //进行分页查询
        PageHelper.startPage(query.getCurrPage(), query.getPageSize());
        PageInfo<Pet> pageInfo = new PageInfo<>(petMapper.selectByExample(example));


        return new PageList<>(pageInfo.getTotal(), pageInfo.getList());

    }

    @Override
    public PetVo getDetailById(Integer id) {
        PetVo petVo = new PetVo();
        Pet tPet = petMapper.selectByPrimaryKey(id);
        PetDetail tPetDetail = petDetailMapper.selectByPrimaryKey(id);
        Shop tShop = shopMapper.selectByPrimaryKey(tPet.getShopId());
        petVo.setPet(tPet);
        petVo.setDetail(tPetDetail);
        petVo.setShop(tShop);
        return petVo;

    }

    @Override
    public Pet findPetById(Long id) {
        return petMapper.selectByPrimaryKey(id);
    }
}
